package formal.tree.recursion;

/**
 * 二叉树的直径
 *
 * @author DengYuan2
 * @create 2021-01-10 15:25
 */
public class E_543 {
    public static void main(String[] args) {
        Integer[] a = {1, 2, 3, 4, 5, 6, null, null, null, null, 7};
//        Integer[] a = {4,-7,-3,null,null,-9,-3,9,-7,-4,null,6,null,-6,-6,null,null,0,6,5,null,9,null,null,-1,-4,null,null,null,-2};
        TreeNode treeNode = TreeNode.generateTree(a);
        int res = diameterOfBinaryTree(treeNode);
        System.out.println(res);

    }

    /**
     * 我的写法-自底向上递归
     */
    public static int max = 0;

    public static int diameterOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        helper(root);
        return max;
    }

    public static int helper(TreeNode root){
        if (root == null) {
            return 0;
        }
        int left = helper(root.left);
        int right = helper(root.right);
        int len = left+right;
        max = Math.max(len,max);
        return 1 + Math.max(left, right);
    }

//    public static int depth(TreeNode root) {
//        if (root == null) {
//            return 0;
//        }
//        return 1 + Math.max(depth(root.left), depth(root.right));
//    }
}
